import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message, Progress } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { 
  BookOutlined, 
  ClockCircleOutlined, 
  TrophyOutlined, 
  DownloadOutlined,
  ReloadOutlined,
  PlayCircleOutlined,
  CheckCircleOutlined 
} from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea } from '@/components/Charts';
import dayjs from 'dayjs';
import { 
  getLearningStatistics, 
  getLearningTrendAnalysis, 
  getCourseCompletionStats,
  getLearningPatternAnalysis,
  exportStatisticsData 
} from '@/services/statisticsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;

const LearningStats: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<STATISTICS.TimeRange>('month');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);
  const [statistics, setStatistics] = useState<STATISTICS.LearningStatistics | null>(null);

  // 获取统计数据
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const params: STATISTICS.StatisticsQueryParams = {
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        granularity: 'day'
      };

      const response = await getLearningStatistics(params);
      if (response.code === 200) {
        setStatistics(response.data);
      } else {
        message.error(response.message || '获取学习统计数据失败');
      }
    } catch (error) {
      console.error('获取学习统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async (type: 'excel' | 'csv' | 'pdf') => {
    try {
      const params: STATISTICS.ExportParams = {
        type,
        data_type: 'learning',
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        include_charts: true
      };

      await exportStatisticsData(params);
      message.success(`${type.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [timeRange, dateRange]);

  // 学习时长趋势图配置
  const studyTimeTrendConfig = {
    data: statistics?.study_time_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#52c41a',
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '学习时长',
        value: `${(datum.value / 3600).toFixed(1)}小时`,
      }),
    },
  };

  // 练习次数趋势图配置
  const practiceAttemptsTrendConfig = {
    data: statistics?.practice_attempts_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#1890ff',
    area: {
      style: {
        fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
      },
    },
  };

  // 准确率趋势图配置
  const accuracyRateTrendConfig = {
    data: statistics?.accuracy_rate_trend || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    color: '#fa8c16',
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '准确率',
        value: `${datum.value}%`,
      }),
    },
  };

  // 课程完成情况表格列配置
  const courseCompletionColumns = [
    {
      title: '课程ID',
      dataIndex: 'course_id',
      key: 'course_id',
      width: 80,
    },
    {
      title: '课程名称',
      dataIndex: 'course_title',
      key: 'course_title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '总报名数',
      dataIndex: 'total_enrollments',
      key: 'total_enrollments',
      width: 100,
    },
    {
      title: '完成数',
      dataIndex: 'completions',
      key: 'completions',
      width: 100,
    },
    {
      title: '完成率',
      dataIndex: 'completion_rate',
      key: 'completion_rate',
      width: 150,
      render: (rate: number) => (
        <Progress 
          percent={rate} 
          size="small" 
          status={rate >= 80 ? 'success' : rate >= 60 ? 'normal' : 'exception'}
        />
      ),
    },
  ];

  // 热门课程表格列配置
  const popularCoursesColumns = [
    {
      title: '课程名称',
      dataIndex: 'course_title',
      key: 'course_title',
      width: 200,
      ellipsis: true,
    },
    {
      title: '报名人数',
      dataIndex: 'enrollment_count',
      key: 'enrollment_count',
      width: 100,
    },
    {
      title: '浏览次数',
      dataIndex: 'view_count',
      key: 'view_count',
      width: 100,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 100,
      render: (rating: number) => `${rating.toFixed(1)}分`,
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="学习统计"
        extra={
          <Space>
            <Select
              value={timeRange}
              onChange={setTimeRange}
              style={{ width: 120 }}
            >
              <Option value="today">今天</Option>
              <Option value="yesterday">昨天</Option>
              <Option value="week">本周</Option>
              <Option value="month">本月</Option>
              <Option value="quarter">本季度</Option>
              <Option value="year">本年</Option>
              <Option value="custom">自定义</Option>
            </Select>
            {timeRange === 'custom' && (
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                format="YYYY-MM-DD"
              />
            )}
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchStatistics}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('pdf')}
              >
                导出PDF
              </Button>
            </Button.Group>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 概览统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总学习次数"
              value={statistics?.overview.total_study_sessions || 0}
              prefix={<BookOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总学习时长"
              value={(statistics?.overview.total_study_time || 0) / 3600}
              precision={1}
              suffix="小时"
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均准确率"
              value={statistics?.overview.average_accuracy_rate || 0}
              precision={1}
              suffix="%"
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="课程完成率"
              value={statistics?.overview.course_completion_rate || 0}
              precision={1}
              suffix="%"
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 学习趋势图表 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="学习时长趋势" loading={loading}>
            <EchartsLine {...studyTimeTrendConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="练习次数趋势" loading={loading}>
            <EchartsArea {...practiceAttemptsTrendConfig} height={250} />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="准确率趋势" loading={loading}>
            <EchartsLine {...accuracyRateTrendConfig} height={250} />
          </ProCard>
        </Col>
      </Row>

      {/* 课程数据分析 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={12}>
          <ProCard title="课程完成情况" loading={loading}>
            <Table
              columns={courseCompletionColumns}
              dataSource={statistics?.course_completion_stats || []}
              rowKey="course_id"
              pagination={{
                pageSize: 8,
                showSizeChanger: false,
                showQuickJumper: false,
              }}
              size="small"
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={12}>
          <ProCard title="热门课程排行" loading={loading}>
            <Table
              columns={popularCoursesColumns}
              dataSource={statistics?.popular_courses || []}
              rowKey="course_id"
              pagination={{
                pageSize: 8,
                showSizeChanger: false,
                showQuickJumper: false,
              }}
              size="small"
            />
          </ProCard>
        </Col>
      </Row>

      {/* 学习偏好分析 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={8}>
          <ProCard title="难度偏好分布" loading={loading}>
            <EchartsPie
              data={statistics?.difficulty_preference || []}
              angleField="count"
              colorField="difficulty"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="学习时段分布" loading={loading}>
            <EchartsColumn
              data={statistics?.learning_patterns.hourly_distribution || []}
              xField="hour"
              yField="count"
              color="#52c41a"
              columnWidthRatio={0.8}
              meta={{
                hour: { alias: '小时' },
                count: { alias: '学习次数' },
              }}
              height={250}
            />
          </ProCard>
        </Col>
        <Col xs={24} lg={8}>
          <ProCard title="学习日期分布" loading={loading}>
            <EchartsColumn
              data={statistics?.learning_patterns.daily_distribution || []}
              xField="day"
              yField="count"
              color="#1890ff"
              columnWidthRatio={0.8}
              meta={{
                day: { alias: '星期' },
                count: { alias: '学习次数' },
              }}
              height={250}
            />
          </ProCard>
        </Col>
      </Row>
    </div>
  );
};

export default LearningStats;
